package com.chengweiyi.security.filter;

import com.chengweiyi.security.entity.SecurityUser;
import com.chengweiyi.security.entity.User;
import com.chengweiyi.security.security.TokenManager;
import com.chengweiyi.servicebase.utils.R;
import com.chengweiyi.servicebase.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author xiao hu die
 * @Date 2022/5/13 16:33
 * @Version 1.0
 */
@Component
/**认证过滤器*/
public class TokenLoginFilter  extends UsernamePasswordAuthenticationFilter {
    /**操作Redis的工具类*/
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(TokenManager tokenManager, RedisTemplate redisTemplate, AuthenticationManager authenticationManager) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.authenticationManager = authenticationManager;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
    }

    /**验证登录名密码方法*/
    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassWord(),
                new ArrayList<>()));
    }
    /**认证成功生成TOKEN并存放到Redis中*/
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
      SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
      /**根据用户名生成Token*/
        String token = tokenManager.createToken(securityUser.getCurrentUserInfo().getUserName());
        /**把用户名称与用户权限放入Redis*/
        redisTemplate.opsForValue().set(securityUser.getCurrentUserInfo().getUserName(),securityUser.getPermissionValueList());
        ResponseUtil.out(response, R.ok().data("token",token));
    }
    /**认证失败调用的方法*/
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
      ResponseUtil.out(response,R.error().message("账号密码不对"));
    }
}
